﻿using adb;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.IO;
using Masuit.Tools.Systems;
using Microsoft.Extensions.Configuration;
using System;
using System.Linq;
using Microsoft.AspNetCore.Authorization;
using PowerStation.RequestModel;
using System.Threading.Tasks;

namespace PowerStation.Controllers
{
    /// <summary>
    /// 资源上传
    /// </summary>
    public class FileController : BaseApi<FileController>
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="log"></param>
        /// <param name="db"></param>
        /// <param name="content"></param>
        /// <param name="configuart"></param>
        public FileController(IHttpContextAccessor content) : base(content)
        {
        }



        /// <summary>
        /// 上传资源
        /// </summary>
        /// <param name="file">文件列表</param>
        /// <param name="typeName">上传类型,监控截图,电站潮流图</param>
        /// <returns></returns>
        [HttpPost("typeName")]
        public async Task<ResultApi<tFiles>> Upload(IFormFile file, string typeName)
        {

            var sf = new SnowFlake();
            tFiles fileModel;
            string contentType = file.ContentType;
            string fileOrginname = file.FileName;//新建文本文档.txt  原始的文件名称
            string fileExtention = Path.GetExtension(fileOrginname);
            string urlPath = "";
            string cdipath = this.configuart["SavePath"];
            if ("监控截图,电站潮流图".Contains(typeName) == false)
            {
                return ResultApi.error<tFiles>(null, "类型出错");
            }
            urlPath = $"{typeName}\\{DateTime.Now:yyyyMMdd}\\";
            cdipath = Path.Combine(cdipath, urlPath);
            if (!Directory.Exists(cdipath))
            {
                Directory.CreateDirectory(cdipath);
            }
            string fileupName = sf.GetLongId() + fileExtention;
            cdipath = Path.Combine(cdipath, fileupName);
            using (var fileSream = new FileStream(cdipath, FileMode.Create, FileAccess.Write))
            {
                using (var searm = file.OpenReadStream())
                {
                    await searm.CopyToAsync(fileSream);
                    fileModel = new tFiles()
                    {
                        addTime = DateTime.Now,
                        fileName = file.FileName,
                        filePath = urlPath + fileupName,
                        fileDomain = typeName,
                        fileType = contentType
                    };
                }
            }

            await this._db.tFiles.AddAsync(fileModel);
            await this._db.SaveChangesAsync();
            return ResultApi.ok(fileModel);
        }


        /// <summary>
        /// 上传文件,base64
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ResultApi<tFiles>> UploadOfBase64(RequestUploadFileBase64Model model)
        {

            return await this.Upload(new RequestUploadFile(new MemoryStream(Convert.FromBase64String(model.fileData))) {
                ContentType = model.contentType,
                FileName = model.fileName,
                Name  = model.fileName
            },model.typeName);
        }


        /// <summary>
        /// 获取文件
        /// </summary>
        /// <param name="fileId"></param>
        /// <returns></returns>
        [HttpGet("fileId")]
        [AllowAnonymous]
        public IActionResult Files(int fileId)
        {
            var m = this._db.tFiles.FirstOrDefault(x => x.fileId == fileId);
            if (m == null)
            {
                this.Response.StatusCode = 401;
                this.Response.WriteAsync("未知文件");
                return null;
            }
            var path = this.configuart["SavePath"] + m.filePath;
            return PhysicalFile(path, m.fileType);
        }
    }
}
